import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin'
import { Park } from './park';
import { UserSettingProvider } from '../user-setting/user-setting';
import { SqliteHelperProvider } from '../sqlite-helper/sqlite-helper';

@Injectable()
export class ParkDataProvider {
  private readonly baseUrl: string = 'https://api.bmob.cn/1';
  private readonly httpHeaders : HttpHeaders =new HttpHeaders({
    'X-Bmob-Application-Id':'0f23034457b7a694277ce9d417af0538',
    'X-Bmob-REST-API-Key':'743577773d54228e84ae14b11573af5a',
    'Content-Type':'applicaton/json'
    });

    

  constructor(public http: HttpClient,
    private userSettingProvider:UserSettingProvider,
    private sqliteHelperProvider: SqliteHelperProvider) {
  }
  
  /**
   * 分页获取景区数据
   * @param num 
   * @param page 
   */
 getParks(num:number,page:number) : Observable<Park[]>{
    let _params = new HttpParams()
    .set('limit', `${num}`)
    .set('skip',`${(page -1)*num}`);
    return this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,
    {headers:this.httpHeaders,params: _params}).map(_=>_['results']);
}
/**
 * 获取一条景区记录
 * @param objectId 
 */
getPark(objectId:string) : Observable<Park>{
  return this.http.get<Park>(`${this.baseUrl}/classes/parks/${objectId}`,{headers:this.httpHeaders});
}
/**
 * 获取记录条数
 */
getCount() : Observable<number>{
  return this.http.get<number>(`${this.baseUrl}/classes/parks?&limit=0&count=1`,{headers:this.httpHeaders}).map(data=>data['count']);
}
/**
 * 获取所有记录
 * @param total 记录总数 
 */
getAllParks(total:number):Observable<Park[][]>{
  let num = 500;
  let all: Observable<Park[]>[] = [];
  for(let index = 0 ; index <= total/num;index++){
    let _params = new HttpParams()
    .set('limit',`${num}`)
    .set('skip',`${index * num}`);
    all[index] = this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,{headers:this.httpHeaders,params:_params}).map(_=>_['results']);
  }
  return Observable.forkJoin(all);
}
/**
 * //获取记录集
 * @param searchPark 
 */
getSearchParks(searchPark:Park[]) : Observable<Park[]>{
  let all : Observable<Park>[] =[];
  for(let i=0;i<searchPark.length; i++){
    all[i] = this.http.get<Park>(`${this.baseUrl}/classes/parks/${searchPark[i].objectId}`,{headers:this.httpHeaders});
   }
   return Observable.forkJoin(all);
}

/**
 * 缓存HTTP数据到本地
 */
  setParksToCache(forceRefresh: boolean = false): Promise<any>{
    return new Promise<any>((resolve,reject)=>{
    this.userSettingProvider.isRefreshData()
    .then(isRefresh=>{
      console.log(`是否刷新：${isRefresh}`);
      console.log(`是否强制刷新：${forceRefresh}`);
      if( forceRefresh || isRefresh){
        this.sqliteHelperProvider.creatOrOpenDb() //打开或新建数据库
        .then(()=>{
          return this.sqliteHelperProvider.executeSql('DELETE FROM parks_lite',[]);//清空原有数据库中的数据，即清空缓存
        })
        .then(()=>{
          return this.getCount().toPromise();//获取远端数据记录数
        })
        .then(total=>{
          return this.getAllParks(total).toPromise();//获取远端数据
        })
        .then(data=>{
          data.forEach((parks)=>{
          console.log(`待加入数据：${parks.length}`);
          let sql = 'INSERT INTO parks_lite (objectId ,name , point)';
          sql += ` SELECT  '${parks[0].objectId}', '${parks[0].name}', '${parks[0].point}'`;
          for(let i = 1; i<parks.length;i++){
           sql += ` UNION ALL SELECT  '${parks[i].objectId}', '${parks[i].name}', '${parks[i].point}'`;
          }
          this.sqliteHelperProvider.executeSql(sql,[]);
          });//插入数据到数据库中

          // data.forEach(parks=>{
          //  parks.forEach(park=>{
          //    //有错
          //    let sql = 'INSERT INTO pakrs_lite(objectId,name,point) VALUES(?,?,?)';//实际要做4w+次插入操作，效率低
          //    let sql_params = [park.objectId,park.name,park.point];
          //    this.sqliteHelperProvider.executeSql(sql,sql_params);
          //  });
          // });
        })
        .then(()=>{
          this.userSettingProvider.setRefreshData();
        })
        .catch(err=>{
          console.log(err);
          reject(err)
        });
      }
      
    });
   });
  }

  /**
   * 从缓存中读取数据
   */
  getParksFromCache():Promise<any>{
    return this.sqliteHelperProvider.creatOrOpenDb()
    .then(()=>{
      return this.sqliteHelperProvider.executeSql('SELECT * FROM parks_lite',[]);
    });
  }
  /**
   * 获取缓存记录数
   */
  getCacheCount(): Promise<any>{
    return this.sqliteHelperProvider.creatOrOpenDb().then(()=>{
      return this.sqliteHelperProvider.executeSql('SELECT COUNT(1) AS count FROM parks_lite',[]);
    });
  }
}
